﻿@model SF.WebClient.Controllers.DatagridExcelDataModel
@{
    ViewBag.Title = "datagrid多行编辑";
    bool hasContent = string.IsNullOrWhiteSpace(Model.ApplyID) ? false : !string.IsNullOrWhiteSpace(Model.content);
}
<script src="~/Scripts/jquery-easyui-extensions/base/jeasyui.extensions.base.loading.js"></script>
<script src="~/Scripts/jquery-easyui-extensions/base/jeasyui.extensions.base.isEasyUI.js"></script>
<link href="~/Scripts/jquery-easyui-extensions/validatebox/jeasyui.extensions.validatebox.css" rel="stylesheet" />
<script src="~/Scripts/jquery-easyui-extensions/validatebox/jeasyui.extensions.validatebox.js"></script>
<script src="~/Scripts/jquery-easyui-extensions/datagrid/jeasyui.extensions.datagrid.rowState.js"></script>
<script src="~/Scripts/jquery-easyui-extensions/datagrid/jeasyui.extensions.datagrid.editors.js"></script>

<script src="~/Scripts/jquery-plugins/ueditor-1.4.3.1/ueditor.config.js"></script>
<script src="~/Scripts/jquery-plugins/ueditor-1.4.3.1/ueditor.all.min.js"></script>

<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'north',border:false" style="height:40px;overflow:hidden;">
        <div class="datagrid-toolbar" style="height:100%;padding:7px;">
            <a id="btnInsert" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">新增一行</a>
            <a id="btnRemove" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true">删除一行</a>
            <a id="btnSave" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true">保存数据行(不交互后台)</a>
            <a id="btnSubmit" class="easyui-linkbutton" data-options="iconCls:'icon-back',plain:true">提交全部数据</a>
            <div id="tempEditContent" style="display:none;">
                @if (hasContent)
                {
                    @Html.Raw(Model.content)
                }
            </div>
        </div>
    </div>
    <div data-options="region:'center',border:false">
        <div class="easyui-layout" data-options="fit:true">
            <div data-options="region:'center'">
                <div class="easyui-layout" data-options="fit:true">
                    <div data-options="region:'north',border:false" style="height:130px;padding:20px;overflow:hidden;">
                        <div style="font-size:22px;font-weight:bolder;width:100%;text-align:center;">
                            采购申请单
                        </div>
                        <form id="PurchaseApplyForm" method="post">
                            <table border="0" style="width:100%;height:auto;margin-top:15px;padding:10px;">
                                <tr>
                                    <td style="width:110px;text-align:right;">申请人：</td>
                                    <td>
                                        <input id="ApplyStaff" name="ApplyStaff" type="hidden" value="@Model.ApplyStaff" />
                                        <input class="easyui-textbox" id="ApplyStaffName" name="ApplyStaffName" data-options="readonly:true" value="@Model.ApplyStaffName" style="width:120px">
                                    </td>
                                    <td style="width: 110px; text-align: right;">编号：</td>
                                    <td>
                                        <input class="easyui-textbox" id="ApplyID" name="ApplyID" value="@(Model.ApplyID)" data-options="readonly:true" style="width:220px">
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:110px;text-align:right;">申请部门：</td>
                                    <td>
                                        <input id="ApplyDepartment" name="ApplyDepartment" type="hidden" value="@Model.ApplyDepartment" />
                                        <input class="easyui-textbox" id="ApplyDepartmentName" name="ApplyDepartmentName" data-options="readonly:true" value="@Model.ApplyDepartmentName" style="width:120px">
                                    </td>
                                    <td style="width:110px;text-align:right;">日期：</td>
                                    <td>
                                        <input class="easyui-textbox" id="ApplyDate" name="ApplyDate" data-options="readonly:true" value="@(Model.ApplyDate.HasValue ? Model.ApplyDate.Value.ToString("yyyy-MM-dd") : string.Empty)" style="width:120px">
                                    </td>
                                </tr>
                            </table>
                        </form>
                    </div>
                    <div data-options="region:'center',border:false" style="border-top-width:1px;">
                        <table id="dgBuyItemList"></table>
                    </div>
                </div>
            </div>
            <div id="theEditorPanel" data-options="region:'east',border:true,split:true,title:'申请内容'" style="width:550px;">
                <div id="editorContainer">

                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {

        var data = [], hasContent = $.string.toBoolean("@hasContent"), infoData = [];

        var dg = $("#dgBuyItemList"),
            defaultRow = { ID: "", Code: "", Name: "", StandardModel: "", ApplyCount: "", Remark: "", Stocks: "" },
            insertPosition = "bottom";

        //根据物资编码获取物资信息
        var ajaxGetInfo = function (code) {
            var target = $.array.first(infoData, function (item) { return item.Code == code });
            if (!target) {
                var info = $.util.requestAjaxData("/Demo/GetDatagridEditTheGoodData", { code: code });
                if (info.Code) {
                    infoData.push(info);
                    target = info;
                }
            }
            return target;
        };

        //设置物资其他列数据
        var setOtherInfo = function (editor, info) {
            if (editor.type == "text") {
                editor.target.val(info[editor.field]);
            }
            else if (editor.type == "validatebox" || editor.type == "numberbox") {
                editor.target[editor.type]("setValue", info[editor.field]);
            }
        };

        //获取其他行的申请数量之和
        var getOtherRowApplyCountTotal = function (exceptRowIndex) {
            var rows = dg.datagrid("getRows"), len = rows.length, total = 0;
            for (var i = 0; i < len; i++) {
                if (i == exceptRowIndex) { continue; }
                if (dg.datagrid("isEditing", i)) {
                    var editor = dg.datagrid("getEditor", { index: i, field: "ApplyCount" }), val = editor.target.numberbox("getValue");
                    if (!$.string.isNullOrWhiteSpace(val)) { total += Number(val); }
                }
                else {
                    var val = rows[i]["ApplyCount"];
                    if (!$.string.isNullOrWhiteSpace(val)) { total += Number(val); }
                }
            }

            return total;
        };

        //更新合计行
        var updateFooter = function (total) {
            dg.datagrid('reloadFooter', [{ Code: '合计', ApplyCount: total }]);
        };

        //自动聚焦到下一个列编辑器
        //thisArg：jQ对象，可以是 editor、editor的容器（因为editor可能不存在）
        //field：列名
        //index：索引号，寻找同行的下一列编辑器时可传递，其他时候不能传递，需根据thisArg去获取
        var autoNextFieldEditorFocus = function (thisArg, field, index) {
            var opts = dg.datagrid("options"),
                panel = dg.datagrid("getPanel"),
                index = index == undefined ? window.parseInt(thisArg.closest("tr[datagrid-row-index]").attr("datagrid-row-index")) : index;
            //console.log("当前列名：" + field);
            //console.log("当前索引：" + index);
            var cellTd = panel.find("div.datagrid-view div.datagrid-body table tr.datagrid-row[datagrid-row-index=" + index + "] td[field=" + field + "]");
            var nextCellTd = cellTd.next();
            if (nextCellTd.length == 0) {
                //下一个列的容器td不存在，视为本行编辑列到达结尾，结束本行编辑
                //console.log("下一个列的容器td不存在，视为本行编辑列到达结尾，结束本行编辑");
                dg.datagrid("endEdit", index);

                var rows = dg.datagrid("getRows");
                if (!rows || !rows.length) { return; }
                var len = rows.length;
                if (index < len - 1) { dg.datagrid("beginEdit", index + 1); } else { $("#btnInsert").click(); }

                return;
            }
            var nextField = nextCellTd.attr("field"),
                nextCell = nextCellTd.find("div.datagrid-cell"),
                editor = dg.datagrid("getEditor", { field: nextField, index: index });
            if (!editor) {
                //下一个列的editor不存在，说明该列无编辑器，寻找下一个列的editor
                autoNextFieldEditorFocus(nextCell, nextField, index);
            }
            else {
                if (editor && editor.actions && $.isFunction(editor.actions.setFocus)) {
                    if ($.isFunction(editor.actions.focusable) && editor.actions.focusable(editor.target[0]) == true) {
                        editor.actions.setFocus(editor.target[0]);
                    }
                    else {
                        //validatebox不可聚焦，跳过，寻找下一个列的editor
                        autoNextFieldEditorFocus(editor.target, nextField, index);
                    }
                } else {
                    editor.target.focus();
                }
            }
        }

        var dgInit = function () {

            var getColumns = function () {
                var result = [];

                var normal = [
                    { field: "ck", checkbox: true },
                    {
                        field: 'Code', title: '物资编码', width: 180,
                        editor: {
                            type: "validatebox",
                            options: {
                                required: true
                            }
                        }
                    },
                    {
                        field: 'Name', title: '名称', width: 180,
                        editor: {
                            type: "validatebox",
                            options: {
                                required: true,
                                readonly: true
                            }
                        }
                    },
                    {
                        field: 'StandardModel', title: '规格型号', width: 100,
                        editor: {
                            type: "validatebox",
                            options: {
                                required: true,
                                readonly: true
                            }
                        }
                    },
                    {
                        field: 'ApplyCount', title: '申请数量', width: 100,
                        editor: {
                            type: "numberbox",
                            options: {
                                required: true
                            }
                        }
                    },
                    {
                        field: 'Remark', title: '备注', width: 100,
                        editor: {
                            type: "text"
                        }
                    },
                    {
                        field: 'Stocks', title: '库存数量', width: 100,
                        editor: {
                            type: "validatebox",
                            options: {
                                readonly: true
                            }
                        }
                    }
                ];
                result.push(normal);

                return result;
            };
            var options = {
                idField: "ID",
                rownumbers: true,
                fitColumns: true,
                fit: true,
                border: false,
                singleSelect: true,
                url: "/Demo/GetDatagridEditData1?id=@(ViewBag.ID)",
                showFooter: true,
                columns: getColumns(),
                // 开始编辑
                onBeginEdit: function (index, row) {
                    //物资编码editor
                    var editor1 = $(this).datagrid("getEditor", { index: index, field: "Code" });
                    var editor2 = $(this).datagrid("getEditor", { index: index, field: "Name" });
                    var editor3 = $(this).datagrid("getEditor", { index: index, field: "StandardModel" });
                    var editor4 = $(this).datagrid("getEditor", { index: index, field: "ApplyCount" });
                    var editor5 = $(this).datagrid("getEditor", { index: index, field: "Remark" });
                    var editor6 = $(this).datagrid("getEditor", { index: index, field: "Stocks" });

                    var editors = [editor1, editor2, editor3, editor4, editor5, editor6];

                    //物资编码，获取物质信息
                    editor1.target.change(function () {
                        var val = $(this).val(), info = ajaxGetInfo(val);
                        if (info) {
                            setOtherInfo(editor2, info);
                            setOtherInfo(editor3, info);
                            setOtherInfo(editor5, info);
                            setOtherInfo(editor6, info);
                        }
                        else {
                            //未找到物资信息
                            var emptyInfo = { Name: "", StandardModel: "", Remark: "", Stocks: "" };
                            setOtherInfo(editor2, emptyInfo);
                            setOtherInfo(editor3, emptyInfo);
                            setOtherInfo(editor5, emptyInfo);
                            setOtherInfo(editor6, emptyInfo);
                            //$.messager.alert("操作提醒", "未找到相应物资信息，请确认输入的物资编码无误。");
                            alert("未找到相应物资信息，请确认输入的物资编码无误。");
                            $.util.delay(function () {
                                editor1.target.focus();
                            });
                        }
                    });

                    //申请数量，统计合计
                    editor4.target.numberbox("textbox").keyup(function () {
                        var val = $(this).val(), otherCountTotal = getOtherRowApplyCountTotal(index);
                        var total = $.string.isNullOrWhiteSpace(val) ? otherCountTotal : (Number(val) + otherCountTotal);
                        updateFooter(total);
                    });

                    //可编辑的编辑器绑定回车事件，目前只考虑 validatebox、text、number 这3种类型的编辑器
                    $.each(editors, function (editorIndex, editorItem) {
                        if (editorItem.type == "validatebox" || editorItem.type == "text") {
                            editorItem.target.keydown(function (e) {
                                if (e.which == 13) {
                                    var val = $(this).val();
                                    if ($.string.isNullOrWhiteSpace(val)) { return; }
                                    autoNextFieldEditorFocus($(this), editorItem.field);
                                }
                            });
                        }
                        else if (editorItem.type == "numberbox") {
                            editorItem.target.numberbox("textbox").keydown(function (e) {
                                if (e.which == 13) {
                                    var val = $(this).val();
                                    if ($.string.isNullOrWhiteSpace(val)) { return; }
                                    autoNextFieldEditorFocus($(this), editorItem.field);
                                }
                            });
                        }
                    });

                    //自动聚焦物资编码列
                    $.util.delay(function () {
                        editor1.target.focus();
                    });
                },
                // 编辑完成之后，但销毁编辑器之前
                onEndEdit: function (index, row, changes) {
                    var existRow = $.array.first(data, function (item) { return item.ID == row.ID; });
                    if (existRow) {
                        $.extend(existRow, row);
                    }
                    else {
                        data.push(row);
                    }
                    //console.log("编辑完成之后的缓存数据集合：");
                    //console.log(data);
                },
                onDblClickRow: function (index, row) {
                    dg.datagrid("beginEdit", index);
                },
                onLoadSuccess: function (dgData) {
                    if (typeof dgData == "Array") {
                        $.each(dgData, function (mn, item) { data.push(item); });
                    }
                    else {
                        $.each(dgData.rows, function (mn, item) { data.push(item); });
                    }
                }
            };

            dg.datagrid(options);

        };

        var getInsertRowIndex = function () {
            return insertPosition == "top" ? 0 : dg.datagrid("getRows").length;
        }

        var editor;

        var ueditorInit = function () {
            var thePanel = $("#theEditorPanel"), opts = thePanel.panel("options"), panelWidth = opts.width, panelHeight = opts.height;
            var width = panelWidth ? panelWidth - 12 : 800, height = panelHeight ? panelHeight - 140 : 500;
            var ue = UE.getEditor("editorContainer", {
                autoHeight: false,
                initialFrameWidth: width, initialFrameHeight: height,
                toolbars: [[
            'fullscreen', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'selectall', 'cleardoc', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', '|',
            'horizontal', 'spechars', '|',
            'inserttable', 'deletetable', '|',
            'preview', 'searchreplace', 'help'
                ]]
            });

            editor = ue;

            if (hasContent) {
                editor.ready(function () {
                    ue.setContent($("#tempEditContent").html());
                });
            }
        };

        var buttonBindEvent = function () {

            $("#btnInsert").click(function () {
                var targetIndex = getInsertRowIndex(), targetRow = $.extend({}, defaultRow, { ID: $.util.guid() });
                dg.datagrid("insertRow", { index: targetIndex, row: targetRow });
                dg.datagrid("beginEdit", targetIndex);
            });

            $("#btnSave").click(function () {
                var rows = dg.datagrid("getRows"), len = rows.length;
                for (var i = 0; i < len; i++) {
                    if (dg.datagrid("isEditing", i)) {
                        dg.datagrid("endEdit", i);
                    }
                }
            });

            $("#btnRemove").click(function () {
                var checkedRows = dg.datagrid("getChecked");
                var row = checkedRows.length > 0 ? checkedRows[0] : undefined;
                if (row) {
                    var rowIndex = dg.datagrid("getRowIndex", row), msg;
                    if (dg.datagrid("isEditing", rowIndex)) {
                        msg = "该行数据正在编辑，确认删除吗？";
                    }
                    else { msg = "确认删除" + row.Name + "吗？"; }

                    $.messager.confirm("删除确认", msg, function (result) {
                        if (result) {
                            dg.datagrid("deleteRow", rowIndex);
                            if ($.string.contains(row.ID, "-")) {
                                $.array.remove(data, row, function (item1, item2) { return item1.ID == item2.ID; });
                            }
                            else {
                                var theRow = $.array.first(data, function (item) { return item.ID == row.ID });
                                theRow.isDeleted = true;
                            }
                            //console.log("删除操作之后的缓存数据集合：");
                            //console.log(data);
                        }
                    });
                } else {
                    $.messager.alert("操作提醒", "请选择要删除的行。");
                }
            });

            $("#btnSubmit").click(function () {
                var rows = dg.datagrid("getRows"), len = rows.length;
                var hasEditing = false, editingIndex = -1;
                for (var i = 0; i < len; i++) {
                    if (dg.datagrid("isEditing", i)) {
                        hasEditing = true; editingIndex = i; break;
                    }
                }
                if (editingIndex > -1 && !dg.datagrid("validateRow", editingIndex)) {
                    $.messager.alert("操作提醒", "尚有数据正在编辑，并且数据验证未通过，请确认编辑后再尝试提交。"); return;
                }

                var msg = hasEditing ? "尚有数据正在编辑，是否自动保存后再提交？" : "确认提交？";

                var callback = function (autoSave) {
                    if (autoSave) {
                        $("#btnSave").click();
                    }
                    //提交
                    var model = $("#PurchaseApplyForm").serializeObject();
                    model.rows = JSON.stringify(data);
                    model.content = editor.getContent();

                    $.easyui.loading({ locale: "body", msg: "正在提交，请稍等..." });
                    $.post("/Demo/DatagridEditSave1", model, function (result) {
                        $.easyui.loaded("body");
                        if (result.success) {
                            console.log("新ID：" + result.newId);
                            $("#ApplyID").textbox("setValue", result.newId);
                            data = [];
                            var oldRows = dg.datagrid("getRows");
                            $.each(oldRows, function (oldIndex, oldRow) {
                                if ($.string.contains(oldRow.ID, "-")) { oldRow.ID = $.string.replaceAll(oldRow.ID, "-", ""); }
                                data.push(oldRow);
                            });
                            $.messager.alert("操作提醒", "提交完成。");

                            //console.log("提交操作之后的缓存数据集合：");
                            //console.log(data);
                        }
                    });
                };

                $.messager.confirm("提交确认", msg, function (result) {
                    if (result) {
                        callback.call(this, hasEditing);
                    }
                });
            });
        };


        dgInit(); buttonBindEvent(); ueditorInit();


    });
</script>
